<?php

declare(strict_types=1);

namespace App\Robot\Crontab;

use Carbon\Carbon;
use Hyperf\DbConnection\Db;

/**
 * 群转播记录删除
 */
class RoomBroadcastCrontab
{
    public function execute(): string
    {
        // 删除一周前的记录
        $limitTime = Carbon::now()->subWeek()->toDateString();
        DB::table('ch_room_broadcast_record')
        ->where('created_at', '<', $limitTime)
        ->orderBy('id')
        ->chunkById(500, function ($chunk) {
            $ids = $chunk->pluck('id')->all();

            DB::transaction(function () use ($ids) {
                DB::table('ch_room_broadcast_record_targets')
                    ->whereIn('record_id', $ids)
                    ->delete();

                DB::table('ch_room_broadcast_record')
                    ->whereIn('id', $ids)
                    ->delete();
            });
        });

        return 'RoomBroadcastCrontab successfully';
    }
}